//# Admin/loginController
//#
//# @description :: Server-side logic for managing admin/logins
//# @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
var passport = require('passport');

module.exports = {

  login: function (req, res) {
    if (req.session.employer) {// 判断是否为企业管理员.
      return res.redirect("/");
    }
    res.view('login', {
      username: '',
      message: req.flash('error'),
      layout: false
    });
  },

  /**
   * for staff login.
   * @param req
   * @param res
   * @param next
   */
  loginProcess: function (req, res, next) {
    req.session.isCompany = true;
    req.session.isAdmin = false;
    passport.authenticate('local', function (err, user, info) {
      if (err) return next(err);
      if (!user) {
        return res.view('login', {
          username: req.body.username,
          message: info.message,
          layout: false
        });
      }
      req.session.employer = user;
      req.session.admin = null;
      return res.redirect('/');
    })(req, res, next);
  },

  /**
   * logout for all
   * @param req
   * @param res
   */
  logout: function (req, res) {
    var url = '/admin/login';
    if(req.session.isCompany) {
      url = '/login'
    }
    if(req.session.isAdmin) {
      url = '/admin/login'
    }
    req.session.isCompany = false;
    req.session.isAdmin = false;
    req.session.employer = null;
    req.session.admin = null;
    res.redirect(url);
  },

};
